package com.example.hxds.odr.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.common.util.PageUtils;
import com.example.hxds.common.util.R;
import com.example.hxds.odr.controller.form.*;
import com.example.hxds.odr.db.pojo.OrderBillEntity;
import com.example.hxds.odr.db.pojo.OrderEntity;
import com.example.hxds.odr.service.OrderService;
import com.google.gson.JsonObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author XUYANG
 * @Date 2024-03-12 16:42
 */
@RestController
@RequestMapping("/order")
@Tag(name = "OrderController",description = "订单模块Web接口")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @PostMapping("/searchDriverTodayBusinessData")
    @Operation(description = "司机当日订单数据查询")
    public R searchDriverTodayBusinessData(@RequestBody @Valid SearchDriverTodayBusinessDataForm form){
        HashMap map = orderService.searchDriverTodayBusinessData(form.getDriverId());
        return R.ok().put("result",map);
    }
    @PostMapping("/insertOrder")
    @Operation(summary = "顾客下单")
    public R insertOrder(@RequestBody @Valid InsertOrderForm form){
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUuid(form.getUuid());
        orderEntity.setCustomerId(form.getCustomerId());
        orderEntity.setStartPlace(form.getStartPlace());
        JSONObject json = new JSONObject();
        json.set("latitude", form.getStartPlaceLatitude());
        json.set("longitude", form.getStartPlaceLongitude());
        orderEntity.setStartPlaceLocation(json.toString());
        orderEntity.setEndPlace(form.getEndPlace());
        json = new JSONObject();
        json.set("latitude", form.getEndPlaceLatitude());
        json.set("longitude", form.getEndPlaceLongitude());
        orderEntity.setEndPlaceLocation(json.toString());
        orderEntity.setExpectsMileage(new BigDecimal(form.getExpectsMileage()));
        orderEntity.setExpectsFee(new BigDecimal(form.getExpectsFee()));
        orderEntity.setFavourFee(new BigDecimal(form.getFavourFee()));
        orderEntity.setChargeRuleId(form.getChargeRuleId());
        orderEntity.setCarPlate(form.getCarPlate());
        orderEntity.setCarType(form.getCarType());
        orderEntity.setDate(form.getDate());

        OrderBillEntity orderBillEntity = new OrderBillEntity();
        orderBillEntity.setBaseMileage(form.getBaseMileage());
        orderBillEntity.setBaseMileagePrice(new BigDecimal(form.getBaseMileagePrice()));
        orderBillEntity.setExceedMileagePrice(new BigDecimal(form.getExceedMileagePrice()));
        orderBillEntity.setBaseMinute(form.getBaseMinute());
        orderBillEntity.setExceedMinutePrice(new BigDecimal(form.getExceedMinutePrice()));
        orderBillEntity.setBaseReturnMileage(form.getBaseReturnMileage());
        orderBillEntity.setExceedReturnPrice(new BigDecimal(form.getExceedReturnPrice()));

        String id = orderService.insertOrder(orderBillEntity,orderEntity);
        return R.ok().put("result", id);
    }
    @PostMapping("/acceptNewOrder")
    @Operation(description = "司机接单")
    public R acceptNewOrder(@RequestBody @Valid AcceptNewOrderForm form){
        String res=orderService.acceptNewOrder(form.getDriverId(),form.getOrderId());
        return R.ok().put("result",res);
    }
    @PostMapping("/searchDriverExecuteOrder")
    @Operation(summary = "查询司机正在进行的订单记录")
    public R searchDriverExecuteOrder(@RequestBody @Valid SearchDriverExecuteOrderForm form){
        Map param= BeanUtil.beanToMap(form);
        HashMap map=orderService.searchDriverExecuteOrder(param);
        return R.ok().put("result",map);
    }
    @PostMapping("/searchOrderStatus")
    @Operation(summary = "查询订单状态")
    public R searchOrderStatus(@RequestBody @Valid SearchOrderStatusForm form) {
        Map param = BeanUtil.beanToMap(form);
        Integer status = orderService.searchOrderStatus(param);
        return R.ok().put("result", status);
    }
    @PostMapping("/searchOrderStartLocationIn30Days")
    @Operation(summary = "查询30天内的上车地点")
    public R searchOrderStartLocationIn30Days() {
        ArrayList<HashMap> res=orderService.searchOrderStartLocationIn30Days();
        return R.ok().put("result", res);
    }

    @PostMapping("/deleteUnAcceptOrder")
    @Operation(summary = "删除没有司机接单的订单")
    public R deleteUnAcceptOrder(@RequestBody @Valid DeleteUnAcceptOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        String result = orderService.deleteUnAcceptOrder(param);
        return R.ok().put("result", result);
    }
    @PostMapping("/searchDriverCurrentOrder")
    @Operation(summary = "查询司机当前订单表单")
    public R searchDriverCurrentOrder(@RequestBody @Valid SearchDriverCurrentOrderForm form) {
        HashMap map = orderService.searchDriverCurrentOrder(form.getDriverId());
        return R.ok().put("result", map);
    }
    @PostMapping("/hasCustomerCurrentOrder")
    @Operation(summary = "查询乘客是否存在当前的订单")
    public R hasCustomerCurrentOrder(@RequestBody @Valid HasCustomerCurrentOrderForm form){
        HashMap res=orderService.hasCustomerCurrentOrder(form.getCustomerId());
        return R.ok().put("result",res);
    }
    @PostMapping("/searchOrderForMoveById")
    @Operation(summary = "查询订单信息用于司乘同显")
    public R searchOrderForMoveById(@RequestBody @Valid SearchOrderForMoveByIdForm form){
        Map param=BeanUtil.beanToMap(form);
        HashMap res=orderService.searchOrderForMoveById(param);
        return R.ok().put("result",res);
    }
    @PostMapping("/arriveStartPlace")
    @Operation(summary = "司机到达上车点更新订单状态")
    public R arriveStartPlace(@RequestBody @Valid ArriveStartPlaceForm form){
        Map param=BeanUtil.beanToMap(form);
        param.put("status",3);
        int res=orderService.arriveStartPlace(param);
        return R.ok().put("rows",res);
    }
    @PostMapping("/confirmArriveStartPlace")
    @Operation(summary = "乘客确认司机到达上车点")
    public R confirmArriveStartPlace(@RequestBody @Valid ConfirmArriveStartPlaceForm form){
        boolean res=orderService.confirmArriveStartPlace(form.getOrderId());
        return R.ok().put("result",res);
    }
    @PostMapping("/startDriving")
    @Operation(summary = "开始代驾")
    public R startDriving(@RequestBody @Valid StartDrivingForm form){
        Map param=BeanUtil.beanToMap(form);
        param.put("status",4);
        int res=orderService.startDriving(param);
        return R.ok().put("rows",res);
    }
    @PostMapping("/updateOrderStatus")
    @Operation(summary = "更新订单状态")
    public R updateOrderStatus(@RequestBody @Valid UpdateOrderStatusForm form) {
        Map param=BeanUtil.beanToMap(form);
        int rows=orderService.updateOrderStatus(param);
        return R.ok().put("rows",rows);
    }
    @PostMapping("/searchOrderByPage")
    @Operation(summary = "查询订单列表")
    public R searchOrderByPage(@RequestBody @Valid SearchOrderByPageForm form) {
        Map param=BeanUtil.beanToMap(form);
        int page = form.getPage();
        int length=form.getLength();
        int start=(page-1)*length;
        param.put("start",start);
        PageUtils res=orderService.searchOrderByPage(param);
        return R.ok().put("result",res);
    }
    @PostMapping("/searchOrderContent")
    @Operation(summary = "查询订单列表")
    public R searchOrderContent(@RequestBody @Valid SearchOrderContentForm form) {
        HashMap res = orderService.searchOrderContent(form.getOrderId());
        return R.ok().put("result",res);
    }
    @PostMapping("/validDriverOwnOrder")
    @Operation(summary = "查询司机是否关联某订单")
    public R validDriverOwnOrder(@RequestBody @Valid ValidDriverOwnOrderForm form) {
        Map param=BeanUtil.beanToMap(form);
        boolean res=orderService.validDriverOwnOrder(param);
        return R.ok().put("result",res);
    }
    @PostMapping("/searchSettlementNeedData")
    @Operation(summary = "查询司机是否关联某订单")
    public R searchSettlementNeedData(@RequestBody @Valid SearchSettlementNeedDataForm form) {
        Map res=orderService.searchSettlementNeedData(form.getOrderId());
        return R.ok().put("result",res);
    }
    @PostMapping("/searchOrderById")
    @Operation(summary = "根据Id查询订单")
    public R searchOrderById(@RequestBody @Valid SearchOrderByIdForm form) {
        Map param= BeanUtil.beanToMap(form);
        HashMap res=orderService.searchOrderById(param);
        return R.ok().put("result",res);
    }
    @PostMapping("/validCanPayOrder")
    @Operation(summary = "检查订单是否可支付")
    public R validCanPayOrder(@RequestBody @Valid ValidCanPayOrderForm form) {
        Map param= BeanUtil.beanToMap(form);
        HashMap res=orderService.validCanPayOrder(param);
        return R.ok().put("result",res);
    }
    @PostMapping("/updateOrderPrepayId")
    @Operation(summary = "更新预支付订单Id")
    public R updateOrderPrepayId(@RequestBody @Valid UpdateOrderPrepayIdForm form) {
        Map param= BeanUtil.beanToMap(form);
        int res=orderService.updateOrderPrepayId(param);
        return R.ok().put("rows",res);
    }
    @RequestMapping("/recieveMessage")
    @Operation(summary = "接收代驾费消息通知")
    public void recieveMessage(HttpServletRequest request, HttpServletResponse response){
//        try {
//            request.setCharacterEncoding("utf-8");
//            Reader reader=request.getReader();
//            BufferedReader bufferedReader=new BufferedReader(reader);
//            String line=bufferedReader.readLine();
//            StringBuilder tmp=new StringBuilder();
//            while (line!=null){
//                tmp.append(line);
//                line=bufferedReader.readLine();
//            }
//            bufferedReader.close();
//            reader.close();
//
//            String xml=tmp.toString();
//            if (WXPayUtil.isSignatureValid(xml,myWXPayConfig.getKey())){
//                Map<String,String> map=WXPayUtil.xmlToMap(tmp.toString());
//                String resCode=map.get("result_code");
//                String returnCode=map.get("return_code");
//                if ("SUCCESS".equals(resCode)&&"SUCCESS".equals(returnCode)){
//                    response.setCharacterEncoding("utf-8");
//                    response.setContentType("application/xml");
//                    Writer writer=response.getWriter();
//                    BufferedWriter bufferedWriter=new BufferedWriter(writer);
//                    bufferedWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
//                    bufferedWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>");
//                    bufferedWriter.close();
//                    writer.close();
//
//                    String uuid = map.get("out_trade_no");
//                    String payId = map.get("transaction_id");
//                    String driverOpenId = map.get("attach");
//                    String payTime = DateUtil.parse(map.get("time_end"), "yyyyMMddHHmmss").toString("yyyy-MM-dd HH:mm:ss");
//
//                    //修改订单状态、执行分账、发放系统奖励
//                    orderService.handlePayment(uuid,payId,driverOpenId,payTime);
//                }else {
//                    response.sendError(500,"数字签名异常");
//                }
//            }
//        } catch (Exception e) {
//            throw new HxdsException("接收微信支付信息失败");
//        }
    }
    @PostMapping("/updateOrderAboutPayment")
    @Operation(summary = "查询司机是否关联某订单")
    public R updateOrderAboutPayment(@RequestBody @Valid UpdateOrderAboutPaymentForm form){
        Map param=BeanUtil.beanToMap(form);
        String res=orderService.updateOrderAboutPayment(param);
        return R.ok().put("result",res);
    }
    @PostMapping("/searchDriverOrderByPage")
    @Operation(summary = "查询司机是否关联某订单")
    public R searchDriverOrderByPage(@RequestBody @Valid SearchDriverOrderByPageForm form){
        Map param=BeanUtil.beanToMap(form);
        int page=form.getPage();
        int length=form.getLength();
        int start=(page-1)*length;
        param.put("start",start);
        PageUtils res=orderService.searchDriverOrderByPage(param);
        return R.ok().put("result",res);
    }
    @PostMapping("/searchCustomerOrderByPage")
    @Operation(summary = "查询司机是否关联某订单")
    public R searchCustomerOrderByPage(@RequestBody @Valid SearchCustomerOrderByPageForm form){
        Map param=BeanUtil.beanToMap(form);
        int page=form.getPage();
        int length=form.getLength();
        int start=(page-1)*length;
        param.put("start",start);
        PageUtils res=orderService.searchCustomerOrderByPage(param);
        return R.ok().put("result",res);
    }

    @PostMapping("/searchCommentIdByOrderId")
    @Operation(summary = "查询司机是否关联某订单")
    public R searchCommentIdByOrderId(@RequestBody @Valid SearchCommentIdByOrderIdForm form){
        String res=orderService.searchCommentIdByOrderId(form.getOrderId());
        return R.ok().put("result",res);
    }

}
